﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 库存盘点服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class InventorycountsService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Inventorycounts> _inventorycountsRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public InventorycountsService(SqlSugarRepository<Inventorycounts> inventorycountsRep, ISqlSugarClient sqlSugarClient)
    {
        _inventorycountsRep = inventorycountsRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询库存盘点 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询库存盘点")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<InventorycountsOutput>> Page(PageInventorycountsInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _inventorycountsRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.CountNumber.Contains(input.Keyword) || u.Remark.Contains(input.Keyword) || u.InventoryDetailRemarks.Contains(input.Keyword) || u.UploadAttachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CountNumber), u => u.CountNumber.Contains(input.CountNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InventoryDetailRemarks), u => u.InventoryDetailRemarks.Contains(input.InventoryDetailRemarks.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadAttachments), u => u.UploadAttachments.Contains(input.UploadAttachments.Trim()))
            .WhereIF(input.InventoryTypeId != null, u => u.InventoryTypeId == input.InventoryTypeId)
            .WhereIF(input.InventoryStartTimeRange?.Length == 2, u => u.InventoryStartTime >= input.InventoryStartTimeRange[0] && u.InventoryStartTime <= input.InventoryStartTimeRange[1])
            .WhereIF(input.InventoryEndTimeRange?.Length == 2, u => u.InventoryEndTime >= input.InventoryEndTimeRange[0] && u.InventoryEndTime <= input.InventoryEndTimeRange[1])
            .WhereIF(input.RepositoryNameId != null, u => u.RepositoryNameId == input.RepositoryNameId)
            .WhereIF(input.Department != null, u => u.Department == input.Department)
            .WhereIF(input.Attn != null, u => u.Attn == input.Attn)
            .WhereIF(input.MakeSingle != null, u => u.MakeSingle == input.MakeSingle)
            .WhereIF(input.CountLocationsIdId != null, u => u.CountLocationsIdId == input.CountLocationsIdId)
            .WhereIF(input.CountQuantity != null, u => u.CountQuantity == input.CountQuantity)
            .WhereIF(input.NumberProfits != null, u => u.NumberProfits == input.NumberProfits)
            .WhereIF(input.NumberLosses != null, u => u.NumberLosses == input.NumberLosses)
            .WhereIF(input.InventoryStatus != null, u => u.InventoryStatus == input.InventoryStatus)
            .LeftJoin<Inventorytype>((u, inventoryType) => u.InventoryTypeId == inventoryType.Id)
            .LeftJoin<Warehouse>((u, inventoryType, repositoryName) => u.RepositoryNameId == repositoryName.Id)
            .LeftJoin<Organization>((u, inventoryType, repositoryName, department) => u.Department == department.Id)
            .LeftJoin<Customermanagement>((u, inventoryType, repositoryName, department, attn) => u.Attn == attn.Id)
            .LeftJoin<UserManagement>((u, inventoryType, repositoryName, department, attn, makeSingle) => u.MakeSingle == makeSingle.Id)
            .LeftJoin<Binlocation>((u, inventoryType, repositoryName, department, attn, makeSingle, countLocations) => u.CountLocationsIdId == countLocations.Id)
            .Select((u, inventoryType, repositoryName, department, attn, makeSingle, countLocations) => new InventorycountsOutput
            {
                Id = u.Id,
                CountNumber = u.CountNumber,
                InventoryTypeId = u.InventoryTypeId,
                InventoryTypeFkDisplayName = $"{inventoryType.InventoryTypeName}",
                InventoryStartTime = u.InventoryStartTime,
                InventoryEndTime = u.InventoryEndTime,
                RepositoryNameId = u.RepositoryNameId,
                RepositoryNameFkDisplayName = $"{repositoryName.WarehouseName}",
                Department = u.Department,
                DepartmentFkDisplayName = $"{department.OrganizationName}",
                Attn = u.Attn,
                AttnFkDisplayName = $"{attn.CustomerName}",
                Remark = u.Remark,
                MakeSingle = u.MakeSingle,
                MakeSingleFkDisplayName = $"{makeSingle.UserName}",
                CountLocationsIdId = u.CountLocationsIdId,
                CountLocationsFkDisplayName = $"{countLocations.BinlocationName}",
                CountQuantity = u.CountQuantity,
                NumberProfits = u.NumberProfits,
                NumberLosses = u.NumberLosses,
                InventoryStatus = u.InventoryStatus,
                ParticipationPrice = u.ParticipationPrice,
                InventoryDetailRemarks = u.InventoryDetailRemarks,
                UploadAttachments = u.UploadAttachments,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取库存盘点详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取库存盘点详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Inventorycounts> Detail([FromQuery] QueryByIdInventorycountsInput input)
    {
        return await _inventorycountsRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加库存盘点 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加库存盘点")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddInventorycountsInput input)
    {
        var entity = input.Adapt<Inventorycounts>();
        return await _inventorycountsRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新库存盘点 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新库存盘点")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateInventorycountsInput input)
    {
        var entity = input.Adapt<Inventorycounts>();
        await _inventorycountsRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除库存盘点 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除库存盘点")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteInventorycountsInput input)
    {
        var entity = await _inventorycountsRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _inventorycountsRep.FakeDeleteAsync(entity);   //假删除
        //await _inventorycountsRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除库存盘点 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除库存盘点")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteInventorycountsInput> input)
    {
        var exp = Expressionable.Create<Inventorycounts>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _inventorycountsRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _inventorycountsRep.FakeDeleteAsync(list);   //假删除
        //return await _inventorycountsRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataInventorycountsInput input)
    {
        var inventoryTypeIdData = await _inventorycountsRep.Context.Queryable<Inventorytype>()
            .InnerJoinIF<Inventorycounts>(input.FromPage, (u, r) => u.Id == r.InventoryTypeId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.InventoryTypeName}"
            }).ToListAsync();
        var repositoryNameIdData = await _inventorycountsRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<Inventorycounts>(input.FromPage, (u, r) => u.Id == r.RepositoryNameId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        var departmentData = await _inventorycountsRep.Context.Queryable<Organization>()
            .InnerJoinIF<Inventorycounts>(input.FromPage, (u, r) => u.Id == r.Department)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        var attnData = await _inventorycountsRep.Context.Queryable<Customermanagement>()
            .InnerJoinIF<Inventorycounts>(input.FromPage, (u, r) => u.Id == r.Attn)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var makeSingleData = await _inventorycountsRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Inventorycounts>(input.FromPage, (u, r) => u.Id == r.MakeSingle)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var countLocationsIdIdData = await _inventorycountsRep.Context.Queryable<Binlocation>()
            .InnerJoinIF<Inventorycounts>(input.FromPage, (u, r) => u.Id == r.CountLocationsIdId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.BinlocationName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "inventoryTypeId", inventoryTypeIdData },
            { "repositoryNameId", repositoryNameIdData },
            { "department", departmentData },
            { "attn", attnData },
            { "makeSingle", makeSingleData },
            { "countLocationsIdId", countLocationsIdIdData },
        };
    }
    
    /// <summary>
    /// 导出库存盘点记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出库存盘点记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageInventorycountsInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportInventorycountsOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "库存盘点导出记录");
    }
    
    /// <summary>
    /// 下载库存盘点数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载库存盘点数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportInventorycountsOutput>(), "库存盘点导入模板", (_, info) =>
        {
            if (nameof(ExportInventorycountsOutput.InventoryTypeFkDisplayName) == info.Name) return _inventorycountsRep.Context.Queryable<Inventorytype>().Select(u => $"{u.InventoryTypeName}").Distinct().ToList();
            if (nameof(ExportInventorycountsOutput.RepositoryNameFkDisplayName) == info.Name) return _inventorycountsRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            if (nameof(ExportInventorycountsOutput.DepartmentFkDisplayName) == info.Name) return _inventorycountsRep.Context.Queryable<TreeParentOutput>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            if (nameof(ExportInventorycountsOutput.AttnFkDisplayName) == info.Name) return _inventorycountsRep.Context.Queryable<Customermanagement>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportInventorycountsOutput.MakeSingleFkDisplayName) == info.Name) return _inventorycountsRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportInventorycountsOutput.CountLocationsFkDisplayName) == info.Name) return _inventorycountsRep.Context.Queryable<Binlocation>().Select(u => $"{u.BinlocationName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入库存盘点记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入库存盘点记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportInventorycountsInput, Inventorycounts>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 盘点类型
                    var inventoryTypeIdLabelList = pageItems.Where(x => x.InventoryTypeFkDisplayName != null).Select(x => x.InventoryTypeFkDisplayName).Distinct().ToList();
                    if (inventoryTypeIdLabelList.Any()) {
                        var inventoryTypeIdLinkMap = _inventorycountsRep.Context.Queryable<Inventorytype>().Where(u => inventoryTypeIdLabelList.Contains($"{u.InventoryTypeName}")).ToList().ToDictionary(u => $"{u.InventoryTypeName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.InventoryTypeId = inventoryTypeIdLinkMap.GetValueOrDefault(e.InventoryTypeFkDisplayName ?? "");
                            if (e.InventoryTypeId == null) e.Error = "盘点类型链接失败";
                        });
                    }
                    // 链接 仓库名称
                    var repositoryNameIdLabelList = pageItems.Where(x => x.RepositoryNameFkDisplayName != null).Select(x => x.RepositoryNameFkDisplayName).Distinct().ToList();
                    if (repositoryNameIdLabelList.Any()) {
                        var repositoryNameIdLinkMap = _inventorycountsRep.Context.Queryable<Warehouse>().Where(u => repositoryNameIdLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.RepositoryNameId = repositoryNameIdLinkMap.GetValueOrDefault(e.RepositoryNameFkDisplayName ?? "");
                            if (e.RepositoryNameId == null) e.Error = "仓库名称链接失败";
                        });
                    }
                    // 链接 所在部门
                    var departmentLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentLabelList.Any()) {
                        var departmentLinkMap = _inventorycountsRep.Context.Queryable<TreeParentOutput>().Where(u => departmentLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Department = departmentLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.Department == null) e.Error = "所在部门链接失败";
                        });
                    }
                    // 链接 经办人
                    var attnLabelList = pageItems.Where(x => x.AttnFkDisplayName != null).Select(x => x.AttnFkDisplayName).Distinct().ToList();
                    if (attnLabelList.Any()) {
                        var attnLinkMap = _inventorycountsRep.Context.Queryable<Customermanagement>().Where(u => attnLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Attn = attnLinkMap.GetValueOrDefault(e.AttnFkDisplayName ?? "");
                            if (e.Attn == null) e.Error = "经办人链接失败";
                        });
                    }
                    // 链接 制单人
                    var makeSingleLabelList = pageItems.Where(x => x.MakeSingleFkDisplayName != null).Select(x => x.MakeSingleFkDisplayName).Distinct().ToList();
                    if (makeSingleLabelList.Any()) {
                        var makeSingleLinkMap = _inventorycountsRep.Context.Queryable<UserManagement>().Where(u => makeSingleLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.MakeSingle = makeSingleLinkMap.GetValueOrDefault(e.MakeSingleFkDisplayName ?? "");
                            if (e.MakeSingle == null) e.Error = "制单人链接失败";
                        });
                    }
                    // 链接 盘点库位
                    var countLocationsIdIdLabelList = pageItems.Where(x => x.CountLocationsFkDisplayName != null).Select(x => x.CountLocationsFkDisplayName).Distinct().ToList();
                    if (countLocationsIdIdLabelList.Any()) {
                        var countLocationsIdIdLinkMap = _inventorycountsRep.Context.Queryable<Binlocation>().Where(u => countLocationsIdIdLabelList.Contains($"{u.BinlocationName}")).ToList().ToDictionary(u => $"{u.BinlocationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.CountLocationsIdId = countLocationsIdIdLinkMap.GetValueOrDefault(e.CountLocationsFkDisplayName ?? "");
                            if (e.CountLocationsIdId == null) e.Error = "盘点库位链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Inventorycounts>>();
                    
                    var storageable = _inventorycountsRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.CountNumber?.Length > 32, "盘点单号长度不能超过32个字符")
                        .SplitError(it => it.Item.Remark?.Length > 200, "备注长度不能超过200个字符")
                        .SplitError(it => it.Item.InventoryDetailRemarks?.Length > 200, "盘点明细备注长度不能超过200个字符")
                        .SplitError(it => it.Item.UploadAttachments?.Length > 2000, "上传附件长度不能超过2000个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
